package lib

import (
	"RMS/app/shop/model"
	"RMS/common"
	"RMS/common/cache"
	"RMS/common/db"
	"bytes"
	"context"
	"encoding/json"
	jsoniter "github.com/json-iterator/go"
	"log"
	"strconv"
)

func ImplAddOrder(ctx context.Context, req *model.AddOrderReq) *model.AddOrderResp {
	resp := &model.AddOrderResp{}

	key := cache.GetCartKey(ctx, strconv.FormatInt(int64(req.Id), 10))
	res, err := cache.RDB.HGetAll(ctx, key).Result()
	if err != nil {
		log.Printf("AddOrder Err := %v\n", err.Error())
		resp.Status = common.ErrCode
		resp.Message = common.AddErrMessage
		return resp
	}
	cache.RDB.Del(ctx, key).Result()

	var total float64
	for _, v := range res {
		detail := make(map[string]interface{})
		decoderr := jsoniter.NewDecoder(bytes.NewReader([]byte(v))) // strings.NewReader(strB)
		decoderr.UseNumber()
		decoderr.Decode(&detail)
		if price, ok := detail["totalPrice"].(json.Number); ok {
			f, _ := price.Float64()
			total += f
		}
	}

	b, _ := jsoniter.Marshal(res)
	order := &model.Order{
		Detail:     string(b),
		TotalPrice: total,
	}

	d := db.NewRmsDBRequest(ctx)
	d = d.Table(db.PmsOrderTable)
	if err := d.Create(order).Error; err != nil {
		log.Printf("AddOrder Err:= %v\n", err.Error())
		resp.Status = common.ErrCode
		resp.Message = common.AddErrMessage
		return resp
	}

	resp.Status = common.SuccessCode
	resp.Message = common.SuccessMessage
	return resp
}
